-- 加载os模块
local os = os

-- 定义MD文件的URL
local md_url = "https://note.ftls.xyz/sum-kkbt.md"

-- 使用wget下载MD文件
os.execute('wget -O ./content/kkbt/sum.md ' .. md_url)

-- 读取MD文件
local file = io.open('./content/kkbt/sum.md', 'r')
if file then
    local lines = {}
    for line in file:lines() do
        table.insert(lines, line)
    end
    file:close()

    -- 并行 wget下载 MD 文件中的所有 URL （markdown 文件） 
    local bashStr = ""
    for _, url in ipairs(lines) do
        local command = 'wget -P ./content/'..url:match("(.*/)")..' https://note.ftls.xyz/' .. url..' &'
        bashStr = bashStr .. '\n' .. command
    end
    bashStr = bashStr .. '\n' .. 'wait'
    os.execute('sh -c "' .. bashStr .. '"')
    print('Finish Download')
end


-- 定义trim函数
local function trim(s)
    return (s:gsub("^%s+", "")):gsub("%s+$", "")
end

-- 定义trim函数
local function trim2(s)
    return (s:gsub("^%s*(.-)%s*$", "%1"))
end

-- 打开文件
local file = io.open('./content/kkbt/sum.md', 'r')
if file then
    -- 读取文件
    local lines = {}
    for line in file:lines() do
        table.insert(lines, line)
    end
    file:close()

    -- 处理每一行
    for i, line in ipairs(lines) do
        line = trim(line)
        line = string.sub(line, 1, string.len(line) - 3)
        line = '[[' .. line .. ']]'
        lines[i] = line
    end

    -- 保存文件
    local new_file = io.open('./content/kkbt/sum.md', 'w')
    if new_file then
        for _, line in ipairs(lines) do
            new_file:write(line .. '\n')
        end
        new_file:write('\n\n'..os.date("%Y-%m-%d %H:%M",os.time() + (8 * 60 * 60))..' 构建\n')
        new_file:close()
    end
end